export function downloadFile(url) {
  if (!url) {
    return;
  }

  const suffix =
    url
      .toString()
      .split(".")
      .pop() || "";
  if (!suffix) {
    return;
  }
  const mimeType = mimeTypeObj[suffix.toLowerCase()];
  if (!mimeType) {
    return window.open(url, "_blank");
  }

  download(url, mimeType);
}

const mimeTypeObj = {
  png: "image/png",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  mp4: "video/mp4",
  pdf: "application/pdf"
};

function download(url, mimeType) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.addEventListener(
    "progress",
    function(obj) {
      if (obj.lengthComputable) {
        var percentComplete = obj.loaded / obj.total;
        console.log((percentComplete * 100).toFixed(2) + "%");
        // 可得到下载进度
      }
    },
    false
  );
  xhr.responseType = "blob"; // 设置返回类型blob
  xhr.onload = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let blob = this.response;
      // 转换一个blob链接
      let u = window.URL.createObjectURL(
        new Blob([blob], {
          type: mimeType
        })
      );
      let a = document.createElement("a");
      a.download = new Date().getTime(); //这里是文件名称，这里暂时用链接代替，可以替换
      a.href = u;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
    }
  };
  xhr.send();
}
